package lock.reentrantLock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 描述：演示公平锁和非公平锁
 */
class printQueue {
    private ReentrantLock lock;
    public printQueue(boolean isFair) {
        lock = new ReentrantLock(isFair);
    }
    public void printService() {
        try {
            lock.lock();
            Long duration = (long) (Math.random() * 1000);
            System.out.println(Thread.currentThread().getName() + "正在打印第1份作业，持续时间：" + duration);
            Thread.sleep(duration); // 模拟耗时操作
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        try {
            lock.lock();
            Long duration = (long) (Math.random() * 1000);
            System.out.println(Thread.currentThread().getName() + "正在打印第2份作业，持续时间：" + duration);
            Thread.sleep(duration); // 模拟耗时操作
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
public class FairLock {
    public static void main(String[] args) throws InterruptedException {
        printQueue printQueue = new printQueue(false);
        Thread[] threads = new Thread[10];
        for (int i = 0; i < 10; i++) {
            threads[i] = new Thread(()->{
                System.out.println(Thread.currentThread().getName() + "启动");
                printQueue.printService();
                System.out.println(Thread.currentThread().getName() + "结束");
            }, "t" + i);
        }
        for (int i = 0; i < 10; i++) {
            threads[i].start();
            Thread.sleep(10);// 保证线程启动顺序
        }
    }
}
